import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:love_app/common/su_dialog.dart';
import 'package:love_app/config/app_color.dart';
import 'package:love_app/routes/application.dart';
import 'package:love_app/service/login_api.dart';
import '../../../common/su.dart';

class LoginInput extends StatefulWidget {
  @override
  _LoginInputState createState() => _LoginInputState();
}

class _LoginInputState extends State<LoginInput> {
  TextEditingController _usernameController = TextEditingController(); // 用户名控制器
  TextEditingController _passwordController = TextEditingController(); // 密码控制器
  FocusNode _usernameFocusNode = new FocusNode(); // 用户名框焦点
  FocusNode _passwordFocusNode = new FocusNode(); // 密码框焦点
  GlobalKey _fromKey = GlobalKey<FormState>(); // form表单key
  bool _usernameInputHasData = false; // 是否显示用户名框后面x
  bool _passwordInputHasShow = false; // 是否显示密码
  // bool _usernameInputStatus = false; // 用户名框的状态
  // bool _passwordInputStatus = false; // 密码框的状态

  BuildContext _context;

  @override
  void initState() {
    // 监听密码框
    _usernameController.addListener(() {
      setState(() {});
    });

    // 监听用户名框
    _passwordController.addListener(() {
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    _usernameFocusNode.unfocus();
    _passwordFocusNode.unfocus();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    // final userInfoModel = Provider.of<UserInfoModel>(context);
    return Container(
      child: SingleChildScrollView(
        child: formWidge(),
      ),
    );
  }

  // 表单内容
  Widget formWidge() {
    return Form(
      key: _fromKey,
      autovalidate: true, // 开启自动验证
      child: Column(
        children: <Widget>[
          phoneInput(),
          pwdInput(),
          forgetPwd(),
          loginButton(),
          ruleText(),
        ],
      ),
    );
  }

  // 手机输入框
  Widget phoneInput() {
    return TextFormField(
      autofocus: true, // 自动对焦
      controller: _usernameController,
      focusNode: _usernameFocusNode,
      cursorColor: ThemeColor,
      inputFormatters: [LengthLimitingTextInputFormatter(11)], // 取消右下角字数统计文字
      decoration: InputDecoration(
        labelText: "手机号码",
        hintText: "请输入手机号码",
        filled: true,
        labelStyle: Su().textStyle(ThemeColor, 35),
        fillColor: Color.fromRGBO(255, 255, 255, 1),
        prefixIcon: Icon(
          Icons.phone_iphone,
          color: ThemeColor,
        ),
        suffixIcon: (_usernameInputHasData)
            ? IconButton(
                icon: Icon(Icons.clear),
                onPressed: () {
                  _usernameController.clear();
                },
                color: ThemeColor,
              )
            : null,
        // 选择的焦点下划线样式
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: ThemeColor),
        ),
        // 未选择焦点下划线样式
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: Color.fromRGBO(224, 224, 224, 1),
          ),
        ),
      ),
      keyboardType: TextInputType.phone,
    );
  }

  Widget pwdInput() {
    // 密码输入框
    return TextFormField(
      autofocus: true, // 自动对焦
      controller: _passwordController,
      focusNode: _passwordFocusNode,
      cursorColor: ThemeColor,
      obscureText: !_passwordInputHasShow, // 是否隐藏
      decoration: InputDecoration(
        labelText: "密码",
        hintText: "请输入登录密码",
        filled: true,
        labelStyle: Su().textStyle(ThemeColor, 35),
        fillColor: Color.fromRGBO(255, 255, 255, 1),
        prefixIcon: Icon(
          Icons.lock,
          color: ThemeColor,
        ),
        suffixIcon: IconButton(
          icon: Icon(
            (_passwordInputHasShow) ? Icons.visibility : Icons.visibility_off,
            color: ThemeColor,
          ),
          onPressed: () {
            setState(() {
              _passwordInputHasShow = !_passwordInputHasShow;
            });
          },
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: ThemeColor),
        ),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: Color.fromRGBO(224, 224, 224, 1),
          ),
        ),
      ),
    );
  }

  // 忘记密码
  Widget forgetPwd() {
    return Container(
      margin: EdgeInsets.only(
        top: ScreenUtil().setHeight(25),
        bottom: ScreenUtil().setHeight(61),
        right: ScreenUtil().setWidth(31),
      ),
      alignment: Alignment.centerRight,
      child: InkWell(
        onTap: () {},
        child: InkWell(
          onTap: () {
            Application.router.navigateTo(context, "/forgetPassword");
          },
          child: Text(
            '忘记密码',
            style:
                TextStyle(fontSize: ScreenUtil().setSp(22), color: ThemeColor),
          ),
        ),
      ),
    );
  }

  // 登录按钮
  Widget loginButton() {
    return InkWell(
      onTap: () {
        _loginFun();
      },
      child: Container(
        height: ScreenUtil().setHeight(80),
        width: ScreenUtil().setWidth(566),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(50.0),
          gradient: _loginButtonIsNoDispaly()
              ? LinearGradient(
                  colors: [
                    Color.fromRGBO(238, 127, 168, 1),
                    Color.fromRGBO(237, 120, 127, 1),
                  ],
                )
              : LinearGradient(
                  colors: [
                    Color.fromRGBO(242, 187, 209, 1),
                    Color.fromRGBO(242, 183, 188, 1),
                  ],
                ),
        ),
        child: Text(
          '登录',
          style: Su().textStyle(Colors.white, 36),
        ),
      ),
    );
  }

  // 满足注册按钮的条件
  bool _loginButtonIsNoDispaly({bool showError = false}) {
    int phoneTextLength = _usernameController.text.length; // 手机号码
    int passwordLength = _passwordController.text.length; // 密码

    if (phoneTextLength != 11) {
      _showInputError(showError, '手机号码错误');
      return false;
    }
    if (passwordLength < 6 || passwordLength > 25) {
      _showInputError(showError, '密码必须6-25位');
      return false;
    }
    return true;
  }

  // 显示输入框不合法提示
  void _showInputError(bool show, String msg) {
    if (show == true) {
      SuDialog.showToast(msg);
    }
  }

  // 点击登录按钮事件
  void _loginFun(){
    if (_loginButtonIsNoDispaly(showError: true) == true) {
      String phone = _usernameController.text;
      String password = _passwordController.text;

      LoginApi api = LoginApi(context: _context);
      api.login(phone, password);
      // if(result.code == 200){
      // }
    }
  }

  // 条例
  Widget ruleText() {
    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(22.0)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            '登录注册表示同意',
            style: TextStyle(fontSize: ScreenUtil().setSp(22.0)),
          ),
          Padding(
            padding: EdgeInsets.only(left: 2),
            child: InkWell(
              onTap: () {},
              child: Text(
                '隐私政策，服务条例',
                style: TextStyle(
                  color: Color.fromRGBO(238, 135, 176, 1),
                  fontSize: ScreenUtil().setSp(22.0),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
